package com.ple.app.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ple.app.jzsf.MainActivity;
import com.ple.app.jzsf.R;
import com.ple.app.util.UserInfo;

import cn.smssdk.SMSSDK;

/**
 * Created by twenj on 2016/11/11.
 */

public class LoginActivity extends Activity {

    private Button loginBtn;
    private EditText editTextUser;
    private EditText editTextPsd;
    private CheckBox checkBoxSavePsd;
    private CheckBox checkBoxAutoLogin;
    private TextView textViewForget;
    private TextView textViewRegister;

    private boolean netState;
    private boolean serverExist;
    private ConnectivityManager manager;

    private static final String USER_NAME = "username";
    private static final String PASSWORD = "password";
    private static final String ISSAVEPASS = "savePassword";
    private static final String AUTOLOGIN = "autoLogin";

    private String userName;
    private String password;

    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //初始化视图
        initView();
        //初始化事件
        initEvents();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        userInfo = new UserInfo(this);//声明UserInfo

        loginBtn = (Button) findViewById(R.id.btn_confirm);//登录
        editTextPsd = (EditText) findViewById(R.id.editText_psd);//密码
        editTextUser = (EditText) findViewById(R.id.editText_user);//用户名
        checkBoxSavePsd = (CheckBox) findViewById(R.id.checkBox_savePsd);//保存密码checkbox
        checkBoxAutoLogin = (CheckBox) findViewById(R.id.checkBox_autLogin);//自动登录
        textViewForget = (TextView) findViewById(R.id.textView_forgetPsd);//忘记密码
        textViewRegister = (TextView) findViewById(R.id.textView_register);//注册帐号
    }

    /**
     * 初始化控件事件
     */
    private void initEvents() {

        /**
         * 检查自动登录和密码保存是否已经勾选，如果选了则自动登录到主界面
         */
        if (userInfo.getBooleanInfo(ISSAVEPASS)) {
            checkBoxSavePsd.setChecked(true);
            editTextUser.setText(userInfo.getStringInfo(USER_NAME));
            editTextPsd.setText(userInfo.getStringInfo(PASSWORD));
            //判断是否需要自动登录
            if (userInfo.getBooleanInfo(AUTOLOGIN)) {
                //默认下是需要自动登录
                checkBoxAutoLogin.setChecked(true);
                //登录
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("username",userInfo.getStringInfo(USER_NAME));
                startActivity(intent);

                finish();
            }
        }

        //用户名 文本框焦点触发事件
        editTextUser.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    //直接将hint置为空，方便用户输入
                    editTextUser.setHint(null);
                } else {
                    //
                }
            }
        });

        //密码 文本框焦点触发事件
        editTextPsd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    editTextPsd.setHint(null);
                } else {
                    //
                }
            }
        });

        //检查并登录
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userName = editTextUser.getText().toString();
                password = editTextPsd.getText().toString();
                if (userName.equals("") || password.equals("")) {
                    Toast.makeText(LoginActivity.this, "请补全用户名或密码！", Toast.LENGTH_LONG).show();
                } else {
                    // 验证Password以及UserName的有效性
                    //VerificationUser(userName,password);
                    if (userName.equals("test") || userName.equals("admin") || userName.equals("user")) {//测试验证
                        if (checkBoxSavePsd.isChecked()) {
                            userInfo.setUserInfo(USER_NAME, userName);
                            userInfo.setUserInfo(PASSWORD, password);
                            userInfo.setUserInfo(ISSAVEPASS, true);
                        }
                        if (checkBoxAutoLogin.isChecked()) {
                            userInfo.setUserInfo(AUTOLOGIN, true);
                        }
                    }else{
                        Toast.makeText(LoginActivity.this,"用户名和密码错误！",Toast.LENGTH_LONG).show();
                    };

                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("username",userName);
                    startActivity(intent);
                    finish();
                }
            }
        });

        //跳转到忘记密码页面
        textViewForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ForgetPsdActivity.class);
                startActivity(intent);
                finish();
            }
        });

        //跳转到注册界面
        textViewRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    /**
     * 1.联网检查
     * 2.访问数据库查询，联网服务端验证
     * @param s1 用户名
     * @param s2 密码
     */
    private void VerificationUser(String s1, String s2) {
        // 检测网络状态，如果网络状况正常，
        // 则对用户名和密码进行验证操作，
        // 否则先设置好网络状态之后再进行登录
        CheckNetState();
        if (netState) {
            //
        } else {
            Toast.makeText(LoginActivity.this, "请检查网络连接状态！", Toast.LENGTH_LONG).show();
            setNetWork();
            VerificationUser(s1, s2);
        }
    }

    /**
     * 返回网络连接状态
     * @return netState
     */
    public boolean CheckNetState() {
        manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            netState = true;
        } else {
            netState = false;
        }
        return netState;
    }

    /**
     * 设置网络连接
     */
    private void setNetWork() {
        //
    }

    public boolean isServerExist() {
        return serverExist;
    }

    /**
     * 在Intent 跳转的时候使用finish()只不过是将此Activity移除了栈，
     * 其占用的资源并没有被释放
     * 使用this.onDestroy()可以解除对资源的占用
     * 但是 此处如果使用onDestroy()会导致之前保存的用户登录数据销毁
     * 因此只有以游客形式登陆的时候可以使用onDestroy()
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //this.onDestroy();
    }
}
